package moltencore.network.game.strategy;

import moltencore.network.game.GameLobby;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import spark.network.protocol.Base;
import moltencore.network.protocol.StartGame;
import moltencore.network.protocol.StartGameResponse;
import moltencore.game.Game;
import org.apache.log4j.Logger;
import spark.utility.OutWrapper;

import java.util.Collection;

public class StartGameStrategy implements IProtocolHandleStrategy<StartGame> {
	private Logger logger = Logger.getLogger(StartGameStrategy.class);

	private Game game;
	private GameLobby lobby;

	public StartGameStrategy(Game game, GameLobby lobby) {
		this.game = game;
		this.lobby = lobby;
	}

	@Override
	public void handle(StartGame packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		StartGameResponse response = new StartGameResponse(packet);
		if(packet.getHostIdentification() != game.getHostIdentification()) {
			logger.warn("Client with identification " + packet.getHostIdentification() + " attempted to start game authenticated by " + game.getHostIdentification());
			response.setStarting(false);
			response.setMessage("You need to be host in order to start a game.");
		}
		else if(game.getState() != Game.State.Created) {
			response.setStarting(false);
			switch(game.getState()) {
				case PreparingForStart:
					response.setMessage("Game is already starting.");
					break;
				case Started:
					response.setMessage("Game has already started.");
					break;
				case Ended:
					response.setMessage("Game has already ended.");
					break;
				default:
					response.setMessage("Game is already past the starting phase.");
					break;
			}
		}
		else {
			lobby.assignTeamsToFields();
			game.setFields(lobby.getFields());
			game.setPlayers(lobby.getPlayers());
			game.commence();
			response.setStarting(true);
		}
		acknowledgement.value = response;
	}
}
